const BloomFilter = require("../template")

function testBloomFilterComplexScenarios() {
  console.log(
    "1. 复杂数据类型处理测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 测试各种复杂数据类型
      const complexItems = [
        JSON.stringify({ name: 'John', age: 30, city: 'NYC' }),
        JSON.stringify([1, 2, 3, 4, 5]),
        JSON.stringify({ nested: { data: [1, 2, 3] } }),
        JSON.stringify({ array: [1, 2, { nested: true }] }),
        JSON.stringify({ null: null, undefined: undefined }),
        JSON.stringify({ boolean: true, number: 42.5 })
      ]
      
      complexItems.forEach(item => bf.add(item))
      
      // 验证所有复杂数据都能正确存储和查询
      const allFound = complexItems.every(item => bf.contains(item))
      
      return allFound &&
             bf.getItemCount() === complexItems.length &&
             !bf.contains(JSON.stringify({ fake: 'data' })) // 不存在的复杂数据
    })()
  )

  console.log(
    "2. 大量数据管理测试:",
    (() => {
      const bf = new BloomFilter(50000, 0.001) // 高精度
      const count = 10000
      
      // 添加大量数据
      for (let i = 0; i < count; i++) {
        bf.add(`large_data_${i}_${Date.now()}_${Math.random()}`)
      }
      
      // 随机访问测试
      const randomIndices = Array.from({ length: 100 }, () => 
        Math.floor(Math.random() * count)
      )
      
      const randomAccessCorrect = randomIndices.every(index => {
        const key = `large_data_${index}_${Date.now()}_${Math.random()}`
        return bf.contains(key) // 由于哈希冲突，可能返回true
      })
      
      // 验证统计信息
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      
      return bf.getItemCount() === count &&
             density > 0 && density <= 1 &&
             rate >= 0 && rate <= 1 &&
             bf.getBitArraySize() > 0
    })()
  )

  console.log(
    "3. 动态负载测试:",
    (() => {
      const bf = new BloomFilter(2000, 0.01)
      
      // 阶段1：添加数据
      for (let i = 0; i < 500; i++) {
        bf.add(`dynamic_${i}`)
      }
      
      const density1 = bf.getBitArrayDensity()
      const rate1 = bf.getFalsePositiveRate()
      
      // 阶段2：继续添加更多数据
      for (let i = 500; i < 1000; i++) {
        bf.add(`dynamic_${i}`)
      }
      
      const density2 = bf.getBitArrayDensity()
      const rate2 = bf.getFalsePositiveRate()
      
      // 阶段3：清空并重新添加
      bf.clear()
      for (let i = 0; i < 200; i++) {
        bf.add(`reset_${i}`)
      }
      
      const density3 = bf.getBitArrayDensity()
      const rate3 = bf.getFalsePositiveRate()
      
      return density2 > density1 && // 密度增加
             rate2 > rate1 && // 假阳性率增加
             density3 < density2 && // 清空后密度降低
             rate3 < rate2 && // 清空后假阳性率降低
             bf.getItemCount() === 200
    })()
  )

  console.log(
    "4. 并发操作模拟测试:",
    (() => {
      const bf = new BloomFilter(3000, 0.01)
      
      // 模拟多个操作同时进行
      const operations = []
      
      // 操作1：批量添加
      for (let i = 0; i < 200; i++) {
        operations.push(() => bf.add(`concurrent_add_${i}`))
      }
      
      // 操作2：批量查询
      for (let i = 0; i < 200; i++) {
        operations.push(() => bf.contains(`concurrent_add_${i}`))
      }
      
      // 操作3：混合操作
      for (let i = 0; i < 100; i++) {
        operations.push(() => bf.add(`concurrent_mixed_${i}`))
        operations.push(() => bf.contains(`concurrent_mixed_${i}`))
      }
      
      // 随机执行操作
      const shuffledOps = operations.sort(() => Math.random() - 0.5)
      shuffledOps.forEach(op => op())
      
      // 验证最终状态
      const finalCount = bf.getItemCount()
      const finalDensity = bf.getBitArrayDensity()
      const finalRate = bf.getFalsePositiveRate()
      
      return finalCount === 300 && // 200 + 100 = 300
             finalDensity > 0 && finalDensity <= 1 &&
             finalRate >= 0 && finalRate <= 1
    })()
  )

  console.log(
    "5. 边界条件处理测试:",
    (() => {
      const bf = new BloomFilter(10, 0.01) // 最小容量
      
      // 测试边界条件
      bf.add('') // 空字符串
      bf.add(' ') // 空格
      bf.add('  ') // 多个空格
      bf.add('a') // 单字符
      bf.add('very_long_string_that_might_cause_issues_with_hash_functions_and_bit_array_operations')
      
      // 验证所有边界数据都能处理
      const boundaryTests = [
        bf.contains(''),
        bf.contains(' '),
        bf.contains('  '),
        bf.contains('a'),
        bf.contains('very_long_string_that_might_cause_issues_with_hash_functions_and_bit_array_operations')
      ]
      
      return boundaryTests.every(test => test === true) &&
             bf.getItemCount() === 5 &&
             bf.getBitArrayDensity() > 0
    })()
  )

  console.log(
    "6. 错误恢复测试:",
    (() => {
      const bf = new BloomFilter(1000, 0.01)
      
      // 正常操作
      bf.add('normal1')
      bf.add('normal2')
      bf.add('normal3')
      
      // 尝试一些边界操作
      bf.add('') // 空字符串
      bf.add('normal1') // 重复添加
      
      // 验证状态
      const count = bf.getItemCount()
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      
      return count === 4 && // 包括空字符串
             density > 0 && density <= 1 &&
             rate >= 0 && rate <= 1 &&
             bf.contains('normal1') === true &&
             bf.contains('') === true
    })()
  )

  console.log(
    "7. 内存效率测试:",
    (() => {
      const bf = new BloomFilter(10000, 0.001) // 高精度，大容量
      
      // 添加大量数据测试内存效率
      const startMemory = process.memoryUsage ? process.memoryUsage().heapUsed : 0
      
      for (let i = 0; i < 5000; i++) {
        bf.add(`memory_test_${i}_${Math.random()}`)
      }
      
      const endMemory = process.memoryUsage ? process.memoryUsage().heapUsed : 0
      const memoryUsed = endMemory - startMemory
      
      // 验证统计信息
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      const bitArraySize = bf.getBitArraySize()
      
      return bf.getItemCount() === 5000 &&
             density > 0 && density <= 1 &&
             rate >= 0 && rate <= 1 &&
             bitArraySize > 0 &&
             memoryUsed < 100 * 1024 * 1024 // 内存使用应该合理
    })()
  )

  console.log(
    "8. 哈希冲突处理测试:",
    (() => {
      const bf = new BloomFilter(100, 0.01) // 小容量，容易冲突
      
      // 添加可能产生冲突的数据
      const conflictItems = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
        'aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'jj',
        'aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj'
      ]
      
      conflictItems.forEach(item => bf.add(item))
      
      // 验证所有数据都能正确查询
      const allFound = conflictItems.every(item => bf.contains(item))
      
      // 验证统计信息
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      
      return allFound &&
             bf.getItemCount() === conflictItems.length &&
             density > 0 && density <= 1 &&
             rate >= 0 && rate <= 1
    })()
  )

  console.log(
    "9. this上下文复杂场景测试:",
    (() => {
      const complexObj = {
        multiplier: 3,
        processComplex: function(items) {
          const bf = new BloomFilter(1000, 0.01)
          items.forEach(item => bf.add(item))
          return bf.getItemCount() * this.multiplier
        }
      }
      
      const testItems = ['complex1', 'complex2', 'complex3', 'complex4', 'complex5']
      const result = complexObj.processComplex(testItems)
      
      return result === 15 // 5 * 3 = 15
    })()
  )

  console.log(
    "10. 复杂对象this绑定场景测试:",
    (() => {
      const complexConfigObj = {
        config: { 
          threshold: 0.1, 
          maxItems: 100 
        },
        processWithComplexConfig: function(items) {
          const bf = new BloomFilter(1000, 0.01)
          items.forEach(item => bf.add(item))
          return bf.getItemCount() <= this.config.maxItems &&
                 bf.getFalsePositiveRate() <= this.config.threshold
        }
      }
      
      const testItems = Array.from({ length: 50 }, (_, i) => `config_item${i}`)
      return complexConfigObj.processWithComplexConfig(testItems) === true
    })()
  )

  console.log(
    "11. 极端负载测试:",
    (() => {
      const bf = new BloomFilter(1, 0.01) // 最小位数组
      
      // 在极端条件下添加大量数据
      for (let i = 0; i < 1000; i++) {
        bf.add(`extreme_${i}`)
      }
      
      // 验证统计信息
      const density = bf.getBitArrayDensity()
      const rate = bf.getFalsePositiveRate()
      const count = bf.getItemCount()
      
      return count === 1000 &&
             density > 0 && density <= 1 &&
             rate >= 0 && rate <= 1 &&
             bf.getBitArraySize() === 1
    })()
  )

  console.log(
    "12. 综合复杂场景测试:",
    (() => {
      const bf = new BloomFilter(5000, 0.01)
      
      // 综合测试：多种操作混合
      const operations = []
      
      // 添加各种类型的数据
      for (let i = 0; i < 100; i++) {
        operations.push(() => bf.add(`mixed_${i}`))
        operations.push(() => bf.add(JSON.stringify({ id: i, data: `data_${i}` })))
        operations.push(() => bf.add(`special_${i}_${Date.now()}`))
      }
      
      // 执行操作
      operations.forEach(op => op())
      
      // 验证最终状态
      const finalStats = {
        count: bf.getItemCount(),
        density: bf.getBitArrayDensity(),
        rate: bf.getFalsePositiveRate(),
        bitArraySize: bf.getBitArraySize(),
        hashFunctionCount: bf.getHashFunctionCount(),
        estimatedCount: bf.estimateItemCount()
      }
      
      // 验证所有统计信息都合理
      return finalStats.count === 300 && // 100 * 3 = 300
             finalStats.density > 0 && finalStats.density <= 1 &&
             finalStats.rate >= 0 && finalStats.rate <= 1 &&
             finalStats.bitArraySize > 0 &&
             finalStats.hashFunctionCount > 0 &&
             finalStats.estimatedCount >= 0 &&
             typeof finalStats.count === 'number' &&
             typeof finalStats.density === 'number' &&
             typeof finalStats.rate === 'number' &&
             typeof finalStats.bitArraySize === 'number' &&
             typeof finalStats.hashFunctionCount === 'number' &&
             typeof finalStats.estimatedCount === 'number'
    })()
  )
}

testBloomFilterComplexScenarios()
